package com.crm.service.impl;

import com.crm.context.BaseContext;
import com.crm.dto.CourseDto;
import com.crm.mapper.CourseMapper;
import com.crm.pojo.Course;
import com.crm.result.PageResult;
import com.crm.service.CourseService;
import com.crm.vo.CourseVo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;


/**
 * 课程业务逻辑层
 */
@Service
@Slf4j
public class CourseServiceImpl implements CourseService {
    //// 定义字符池，包括大小写字母和数字
        private static final String CHAR_POOL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        private static final int STRING_LENGTH = 5; // 字符串长度
    @Autowired
    private CourseMapper courseMapper;


    @Override
    public PageResult getCourse( CourseDto dto ) {
        log.info("课程分页查询第{}页，每页{}条记录",dto.getPageNum(),dto.getPageSize());
        PageHelper.startPage(dto.getPageNum(),dto.getPageSize());
        Page<CourseVo> page = (Page<CourseVo>) courseMapper.getCourse(dto);
        PageResult pageResult = new PageResult(page.getTotal(), page.getResult());
        return pageResult;
    }



    @Override
    public void addCourse(CourseDto dto) {
        Course course=new Course();
        BeanUtils.copyProperties(dto,course);
        //补齐数据
        String code = generateRandomString(STRING_LENGTH);
        course.setCreateBy(BaseContext.getCurrentUserName());
         course.setCode(code);
        courseMapper.addCourse(course);

    }

    @Override
    public void deleteCourse(Integer id) {
        courseMapper.deleteCourse(id);

    }
    /**
     * 查询所有课程信息
     *
     * @return
     */
    @Override
    public List<Course> queryList() {
        return courseMapper.queryList();
    }

    @Override
    public Course queryById(Integer id) {
        return courseMapper.queryById(id);
    }

    @Override
    public void updateCourse(Course course) {
        courseMapper.updateCourse(course);
    }

    /**
     * 生成5位随机的编号
     * @param length
     */
    private static String generateRandomString(int length) {
        Random random = new Random();
        StringBuilder sb = new StringBuilder(length);

        for (int i = 0; i < length; i++) {
            int index = random.nextInt(CHAR_POOL.length());
            sb.append(CHAR_POOL.charAt(index));
        }
        return sb.toString();
    }



}
